package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
)

func main() {
	http.HandleFunc("/login", jsonReqRsp)
	s := &http.Server{
		Addr:           ":9090",
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	err := s.ListenAndServe()
	if err != nil {
		log.Fatal("listenAndServe: ", err)
	} else {
		fmt.Println("Server listening on 9099！")
	}

}

type ResData struct {
	Code     int    `json:"code"`
	Message  string `json:"message"`
	Username string `json:"username"`
	Password string `json:"password"`
}
type LoginInfo struct {
	Username string `json:"username"`
	Password string `json:"Password"`
}

// curl  -H "Content-Type:application/json" -X POST  -d  '{"opttype":1 ,"data": { "systemName": "systemName111", "account": ["zgx001", "ZGX00000", "ZGX00001"]} }' -i  'http://127.0.0.1:9090/x'
func jsonReqRsp(w http.ResponseWriter, r *http.Request) {
	var reqdata LoginInfo

	// 调用json包的解析，解析请求body
	if err := json.NewDecoder(r.Body).Decode(&reqdata); err != nil {
		r.Body.Close()
		log.Fatal(err)
	}
	res := ResData{Code: 404,
		Message:  "username or password error",
		Username: reqdata.Username,
		Password: reqdata.Password}
	if reqdata.Username == "zhb" && reqdata.Password == "123" {
		jsonStr, _ := json.Marshal(reqdata)
		log.Println("req json: ", string(jsonStr))

		res = ResData{Code: 200, Message: "login success", Username: "zhb", Password: "123"}
	}

	// 返回json字符串给客户端
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(res)
}
